package com.shensi.appCollect.utils.tonglianpay.tlfusclasspay.util;

import lombok.Cleanup;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.StringJoiner;
import java.util.stream.Collectors;

/**
 * @author zzq
 * @version 1.0.0
 * @Title {@link}
 * @Description
 * @date 2020/5/26
 */
@Slf4j
public class HttpUtils {

    public static String post(String url, Map<String, String> parameters) throws IOException {
        @Cleanup CloseableHttpClient client = httpClientBuilder().build();
        HttpPost post = new HttpPost(url);
        List<NameValuePair> pairList = parameters.entrySet().stream()
            .map(entry -> new BasicNameValuePair(entry.getKey(), entry.getValue()))
            .collect(Collectors.toList());
        StringJoiner requestBody = new StringJoiner("&");
        for (NameValuePair each : pairList) {
            requestBody.add(StringUtils.join(each.getName(), "=", each.getValue()));
        }
        log.info("Request url : [{}], parameters : [{}]", url, requestBody);
        post.setEntity(new UrlEncodedFormEntity(pairList, StandardCharsets.UTF_8));
        @Cleanup CloseableHttpResponse execute = client.execute(post);
        int statusCode = execute.getStatusLine().getStatusCode();
        if (statusCode != HttpStatus.SC_OK) {
            throw new IOException(
                "Http request error, error message : [" + execute.getStatusLine().getReasonPhrase() + "]");
        }
        String result = Objects.isNull(execute.getEntity()) ? "" : EntityUtils.toString(execute.getEntity(),
            StandardCharsets.UTF_8.toString());
        log.info("Response body : [{}]", result);
        return result;
    }

    private static HttpClientBuilder httpClientBuilder() {
        return HttpClients.custom()
            .disableAutomaticRetries()
            .setDefaultRequestConfig(defaultRequestConfig());
    }

    private static RequestConfig defaultRequestConfig() {
        return RequestConfig.custom()
            .setConnectTimeout(30_000)
            .setSocketTimeout(60_000)
            .setConnectionRequestTimeout(5_000)
            .build();
    }

}
